package com.lanzuo.pana.adapter.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.experimental.UtilityClass;

import java.util.*;

@UtilityClass
public class SpiFileParsePanelUtil {

    private static final String BOARD_TARGET_SECTION = "[BOARD_INSP_RESULT]";
    private static final String BOARD_SECTION_END = "[BOARD_INSP_RESULT_END]";
    private static final String PANEL_TARGET_SECTION = "[PANEL_INSP_RESULT]";
    private static final String PANEL_SECTION_END = "[PANEL_INSP_RESULT_END]";
    private static final String PCS_SN = "PcsSn";
    private static final String PCS_NUM = "PcsNum";

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 从文本行列表中提取 BOARD_NO 和 BARCODE，返回 JSON 字符串
     *
     * @param lines 文件按行分割后的列表
     * @return JSON 字符串，格式：[{"BOARD_NO":"1","BARCODE":"P05..."}, ...]
     * @throws JsonProcessingException 序列化异常
     */
    public static JSONArray extractBoardBarcodeAsJson(List<String> lines) {
        List<Map<String, String>> result = extractBoardBarcode(lines);
//        String jsonResult = objectMapper.writeValueAsString(result);
        return new JSONArray(result);
    }

    /**
     * 提取为 List<Map<String, String>>
     */
    public static List<Map<String, String>> extractBoardBarcode(List<String> lines) {
        if (lines == null) return Collections.emptyList();

        boolean inTargetSection = false;
        List<String> dataLines = new ArrayList<>();
        String headerLine = null;

        for (String line : lines) {
            if (line == null) continue;
            line = line.trim();

            if (line.equals(PANEL_TARGET_SECTION)) {
                inTargetSection = true;
                continue;
            }

            if (line.equals(PANEL_SECTION_END)) {
                inTargetSection = false;
                break; // 可提前退出
            }

            if (!inTargetSection) continue;

            // 跳过空行
            if (line.isEmpty()) continue;

            // 第一个非空行是表头
            if (headerLine == null) {
                headerLine = line;
                continue;
            }

            // 后续为数据行
            dataLines.add(line);
        }

        if (headerLine == null || dataLines.isEmpty()) {
            return Collections.emptyList();
        }

        // 解析表头
        String[] headers = parseCsvLine(headerLine);
        int boardNoIndex = -1;
        int barcodeIndex = -1;

        for (int i = 0; i < headers.length; i++) {
            String header = headers[i].trim();
            if ("BOARD_NO".equalsIgnoreCase(header)) {
                boardNoIndex = i;
            } else if ("BARCODE".equalsIgnoreCase(header)) {
                barcodeIndex = i;
            }
        }

        if (boardNoIndex == -1 && barcodeIndex == -1) {
            throw new IllegalArgumentException("Missing required columns: BOARD_NO and BARCODE in header");
        }

        // 解析数据行
        List<Map<String, String>> result = new ArrayList<>();
        int i = 1;
        for (String dataLine : dataLines) {
            String[] values = parseCsvLine(dataLine);
            Map<String, String> row = new HashMap<>();

//            String boardNo = (boardNoIndex < values.length) ? values[boardNoIndex].trim() : "";
            String barcode = (barcodeIndex < values.length) ? values[barcodeIndex].trim() : "";

            // 可选：跳过空值行
            if (barcode.isEmpty()) {
                continue;
            }

            row.put(PCS_NUM, i + "");
            row.put(PCS_SN, barcode);
            result.add(row);

            i++;
        }

        return result;
    }

    /**
     * 简单 CSV 行解析（不处理引号内逗号，适用于你的场景）
     */
    private static String[] parseCsvLine(String line) {
        // 如果你的数据中可能包含逗号在引号内，需用更复杂的解析器
        // 当前示例数据无此情况，用 split 即可
        return line.split(",", -1); // -1 保留尾部空字段
    }

    // ===== 示例用法 =====
    public static void main(String[] args) throws JsonProcessingException {
        List<String> lines = Arrays.asList(
                "[INFO]",
                "LINE_NAME,MACHINE_SN,MACHINE_NAME,OPERATOR_ID",
                "line1,ParmiMachineSN,MACHINE001,manager",
                "[INFO_END]",
                "",
                "[PANEL_INSP_RESULT]",
                "MODEL_NAME,MODEL_CODE,PANEL_SIDE,INDEX,BARCODE,DATE,START_TIME,END_TIME,DEFECT_NAME,DEFECT_CODE,RESULT,track",
                "PSU6625-336-061-PDU-C5,,BOTTOM,4,P05.68.026737.0003202508140600458004,20250927,19:00:05,19:00:19,,,OK,1",
                "[PANEL_INSP_RESULT_END]",
                "",
                "[BOARD_INSP_RESULT]",
                "BOARD_NO,BARCODE,DEFECT_NAME,DEFECT_CODE,BADMARK,RESULT,Component_Name,Height(um)",
                "1,P05.68.026737.0003202508140600458004,,,NO,OK",
                "2,P05.68.026737.0003202508140600458005,,,NO,OK",
                "3,P05.68.026737.0003202508140600458006,,,NO,OK",
                "4,P05.68.026737.0003202508140600458003,,,NO,OK",
                "5,P05.68.026737.0003202508140600458002,,,NO,OK",
                "6,P05.68.026737.0003202508140600458001,,,NO,OK",
                "[BOARD_INSP_RESULT_END]",
                "",
                "[COMPONENT_INSP_RESULT]",
                "BOARD_NO,LOCATION_NAME,PIN_NUMBER,POS_X,POS_Y,DEFECT_NAME,DEFECT_CODE,RESULT",
                "1,D1,,77.008,42.750,,,OK",
                "[COMPONENT_INSP_RESULT_END]"
        );

        JSONArray json = extractBoardBarcodeAsJson(lines);
        System.out.println(JSONUtil.toJsonPrettyStr(json));
    }

}
